<?php
	/**
	 * Elgg form - product
	 * 
	 * @package Elgg SocialCommerce
	 * @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU Public License version 2
	 * @author Cubet Technologies
	 * @copyright Cubet Technologies 2009-2010
	 * @link http://elgghub.com/
 	**/
	
	global $CONFIG;
	
	/*
	$test_arr = array(
			array (
			'path' => "actual_path1",
			'order' => "1"
			), 
			array (
			'path' => "actual_path3",
			'order' => "3"
			),
			array (
			'path' => "actual_path2",
			'order' => "2"
			)			
			 );*/
			 /*
			 for ($x=0; $x<3; $x++){
			 	$path = "actual_path".($x + 1);
			 	$order = $x + 1;
			 $new_entry = array('path' => "$path", 'order' => "$order");
			$person[] = $new_entry;			 	
			 }
 
			echo "_______";
			//print_r($person[0]); 
			print_r($person[0]['path']);
			echo "_______";	
	class MyProduct extends ElggObject {
	
	    public function setImages(array $images) {
	
	        $this->images = serialize($images);
	
	    }

	public function getImages() {
	return unserialize($this->images);
	    }
	} 			 
			 
											  
	$test = New ElggObject();
	$test->images = serialize($test_arr);

	$test->save();
	$new_guid = $test->getGUID();
	$newEntity = get_entity($new_guid);
	
	$arr = unserialize($newEntity->images);
	*/
//	print_r($arr);
	//print_r($newEntity);

	//print_r($arr[0]);
/*
	$new_array = array();
	$new_array = $newEntity->images;
	print_r($new_array[0]);*/
	//print_r($new_array);
	//print_r($new_array[0]['path']);



	// Set title, form destination
		if (isset($vars['entity'])) {
			$title = sprintf(elgg_echo("stores:editpost"),$object->title);
			$action = "{$CONFIG->pluginname}/edit";
			$title = $vars['entity']->title;
			$body = $vars['entity']->description;
			$taxrate_name_cnty = $vars['entity']->countrycode;
			$price = $vars['entity']->price;
			//print_r("9  ".$price."  9");
			$base_stock = $vars['entity']->base_stock;
			$category = $vars['entity']->category;
			$quantity = $vars['entity']->quantity;
			$tags = $vars['entity']->tags;
			$access_id = $vars['entity']->access_id;
			$product_type_id = $vars['entity']->product_type_id;		//to be removed, subcategory instead
			if($product_type_id <= 0)
				$product_type_id = 2;
			$rating_av = $vars['entity']->rating_av;
			$product_cat = $vars['entity']->product_cat;
			$date_from = $vars['entity']->date_from;
			$date_until = $vars['entity']->date_until;
			$units = $vars['entity']->units;
			$images = unserialize($vars['entity']->images);
 			sort_array($images);
		} else  {
			$title = elgg_echo("stores:addpost");
			$action = "{$CONFIG->pluginname}/add";
			$tags = "";
			$title = "";
			$body = "";
			$base_stock = "";
			$access_id = 2;
			$price = "not disclosed";		//	contact producer link to be included later
//			$product_type_id = 2;			// 	to be removed
			$product_cat = "";				//	product category
			$rating_one = 0;				//	add rating
			$rating_av = 0;					//	rating average					
			$product_subcat = "";			//	ads subcategory
			$people = array();				//	people who purchased the product array of GUIDs
			$date_from = "all year";
			$date_until = "all year";
			$units = "";
			
		}

	// Just in case we have some cached details							// need to revise AB
		if (isset($vars['product'])) {
			//unset($_SESSION['product']);
			$title = $vars['product']['storestitle'];
			//$product_type_id = $vars['product']['product_type_id'];
			$category = $vars['product']['storescategory'];
			
			$body = $vars['product']['storesbody'];
			$tags = $vars['product']['storestags'];
			$access_id = $vars['product']['access_id'];
			//$product_cat = $vars['product']['product_cat'];	
				
			// String date from and until added AB
			$date_from =  $vars['product']['date_from'];
			$date_until =  $vars['product']['date_until'];
			
			// defined in start.php
			$product_fields = $CONFIG->product_fields[2];  
			if (is_array($product_fields) && sizeof($product_fields) > 0){
				foreach ($product_fields as $shortname => $valtype){
					if($valtype['field'] != 'file')
						$_SESSION['product'][$shortname] = get_input($shortname);
				}
			}
			
			$price = $vars['product']['price'];
			$units = $vars['product']['units'];
			$base_stock = $vars['product']['base_stock'];
			$quantity = $vars['product']['quantity'];
			
			
		}
		
		$chk_tax_type = '';				//not in use
		$country_details = '';			//not in use
		
		//need to investigate - nothing spoted in there so far
		$options = array('types'			=>	"object",
						'subtypes'			=>	"splugin_settings",
					);
		$splugin_settings = elgg_get_entities($options);



        $title_label = elgg_echo('title');
        $title_textbox = elgg_view('input/text', array('internalname' => 'storestitle', 'value' => $title));
        
        //this will be omitted
        //$product_type = elgg_view('input/product_type', array('internalname' => 'product_type_id', 'value' => $product_type_id));
        
        // added category
        //$product_cat = elgg_view('input/product_cat', array('internalname' => 'product_cat', 'value' => $product_cat));
        
        //echo ($product_cat);
        
        

        
        // country code disabled
 /*       
        $country_name = elgg_echo('country');
        $country_label = "<label><span style='color:red'>*</span>{$country_name}</label><br />";
        $country_list = "<select name='tax_country' id='tax_country' >";
            if($CONFIG->country){
			foreach ($CONFIG->country as $country){
				if($taxrate_name_cnty == $country['iso3']){
					$selected = "selected";
				}else {
					$selected = "";
				}
				$country_list .= "<option value='".$country['iso3']."' ".$selected.">".$country['name']."</option>";
			}	
		}
        $country_list .= "</select>";
*/
	
        /**
         * prepare list of available categories
         * later on product_type_i to be cleaned
         */
		$options = array(	//'metadata_name_value_pairs'	=>	array('product_type_id' => $product_type_id),
						'types'				=>	"object",
						'subtypes'			=>	"category",						
						'limit'				=>	9999,
						
					);
		$category_lists = elgg_get_entities_from_metadata($options);
	
        
        /**
         * prepare list of categories to dropdown menu
         */
        $options_values = array();
        if($category_lists){
        	foreach ($category_lists as $category_list){
        		$options_values[$category_list->guid] = $category_list->title;
        	}	
        }
        
        //print_r($options_values);	
        				
        $category_label = elgg_echo('category');
        
		/**
		 * creates element to display category drop down menu
		 */	        
        if(!empty($category_lists)){
			$category_view = elgg_view('input/pulldown', array('internalname' => 'storescategory', 
													  'value' => "$category", 
													  'js' => "id='storescategory'", 
													  'options_values' => $options_values));
        }else{
        	$category_view = elgg_echo('no:category');	
        }
        
        //what is mimetype?   // this is upload file part - should be omitted
        /*
        if (($action == "{$CONFIG->pluginname}/add" && $vars['entity']->mimetype == "")||($vars['entity']->guid > 0 && $vars['entity']->mimetype == "")) {
			$upload_label = elgg_echo('stores:file');
	        $upload_input = elgg_view("input/file",array('internalname' => 'upload'));
			$form_upload = <<<EOT
				<p>
					<label><span style="color:red">*</span>$upload_label</label><br />
		                        $upload_input
				</p>
EOT;
			//now here if there is already a image uploaded 
		}elseif ($vars['entity']->guid > 0 && $vars['entity']->mimetype != ""){
			$upload_label = elgg_echo('stores:file');
			$upload_input = elgg_view("{$CONFIG->pluginname}/icon", array("mimetype" => $vars['entity']->mimetype, 'thumbnail' => $vars['entity']->thumbnail, 'file_guid' => $vars['entity']->guid));
			$form_upload = <<<EOT
				<p>
					<label><span style="color:red">*</span>$upload_label</label><br />
		                        $upload_input
				</p>
EOT;
		}
		if ($vars['entity']->guid > 0){
			$uploaded_image = elgg_view("{$CONFIG->pluginname}/image", array(
										'entity' => $vars['entity'],
										'size' => 'small',
										'display'=>'image'
									  )
								);
		}
		*/
        
        //upload product image
        $image_label = elgg_echo('product:image');
        $image_input = elgg_view("input/file",array('internalname' => 'product_image', 'js' => 'onChange="javascript:add_file(this.value);"'));
        
        $text_label = elgg_echo('stores:text');
        $text_textarea = elgg_view('input/longtext', array('internalname' => 'storesbody', 'value' => $body));
       
        
        $fields = '';
		$product_fields = $CONFIG->product_fields[2];
		
		if (is_array($product_fields) && sizeof($product_fields) > 0){
			//if($CONFIG->debug)
			//{print_r($product_fields);}	// prints product fields 
			foreach ($product_fields as $shortname => $valtype){
				$value = $vars['entity']->$shortname;
				//print_r($value." e");									//xx
				if ($shortname=="upload") continue;						// no upload fix
				if (isset($vars['product']))
					$value = $vars['product'][$shortname];
				//print_r($value." i");									//xx
					
				if($valtype['mandatory'] == 1){
					$mandetory = '<span style="color:red">*</span>';	
				}else{
					$mandetory = '';	
				}
				
				//if (!isset($value)) echo($value."*_uuu");	// DP
				
				//shows upload field and price field
				//shortname is array of field name like upload price
				//value contains value from previous session if any
				//retrieved from vars['entity']
				
				$fields .= '<p><label>'.$mandetory.elgg_echo('product:'.$shortname).'</label><br />';
				
				if($vars['entity']->mimetype != "" && $shortname == 'upload' && $valtype['field'] == 'file'){
					$fields .= "<div style='float:left;'>".elgg_view("{$CONFIG->pluginname}/icon", array("mimetype" => $vars['entity']->mimetype, 'thumbnail' => $vars['entity']->thumbnail, 'stores_guid' => $vars['entity']->guid))."</div>";
					$fields .= "<div class='change_product_file'><a href='javascript:void(0);' onclick='load_edit_product_detaile();'><b>".elgg_echo('product:edit:file')."</a></a></div><div class='clear'></div>";
					$fields .= "<div id='product_file_change'>".elgg_view("input/{$valtype['field']}",array(
															'internalname' => $shortname,
															'value' => $value,
															)).'</div>';
				}else if ($shortname == 'price'){
					$fields .= elgg_view("input/{$valtype['field']}",array(
															'internalname' => $shortname,
															'value' => $value,

															));		
				
				} else {	
					//dropdown menu created from units array defined in start
					$fields .= elgg_view("input/{$valtype['field']}",array(
															'internalname' => $shortname,
															'value' => $units,
															'options_values' => $valtype['units']
															));
															//echo("yyyyyyyyyyyyyyyyyyyyyyyyyyyy");
															//print_r($shortname);
															//print_r($valtype['units'][$units]);
															//print_r($product_fields);
															//echo("yyyyyyyyyyyyyyyyyyyyyyyyyyyy");
																														
				}
				$fields .= '</p>';
			}
		}
  
        $tag_label = elgg_echo('tags');
        $tag_input = elgg_view('input/tags', array('internalname' => 'storestags','value' => $tags));
        
        $date_from_label = elgg_echo('date:from');
        $date_from_input = elgg_view('input/scalendar', array('internalname' => 'date_from','value' => $date_from));
        
        $date_until_label = elgg_echo('date:until');
        $date_until_input = elgg_view('input/scalendar', array('internalname' => 'date_until','value' => $date_until));
        
        $access_label = elgg_echo('access');
        $access_input = elgg_view('input/access', array('internalname' => 'access_id', 'value' => $access_id));
        
        $submit_input = elgg_view('input/submit', array('internalname' => 'submit', 'value' => elgg_echo('save')));

        if (isset($vars['container_guid']))
			$entity_hidden = "<input type=\"hidden\" name=\"container_guid\" value=\"{$vars['container_guid']}\" />";
		if (isset($vars['entity']))
			$entity_hidden .= "<input type=\"hidden\" name=\"stores_guid\" id=\"stores_guid\" value=\"{$vars['entity']->getGUID()}\" />";
			
		$entity_hidden .= elgg_view('input/securitytoken');
		$post_url = $CONFIG->wwwroot."mod/{$CONFIG->pluginname}/onchange_product_type.php";
		if(!$vars['entity']->guid)
			$id = 0;
		else 
			$id = $vars['entity']->guid;
		
		
		//$cstom_fields = elgg_view("custom_field/view",array('entity'=>$vars['entity'],'entity_type'=>$product_type_id));
		/*$num_images = count($images);
		if($num_images>0){
			$display = "block";
		}
		else{
			$display = "none";
		}
		for ($x=0; $x<$num_images;$x++){
			$image .= "<option value='file_".($x+1)."'>".$images[$x]['path']."large.jpg</option>";
		}
			*/
			
			
		//build table rows of images that have already been uploaded
		$x = 1;
		$testy = $images;
		foreach ($images as $image){
			
			$table_row .= "<tr><td>".elgg_view("{$CONFIG->pluginname}/image", array(
												'entity' => $vars['entity'],
												'size' => 'medium',
												'display' => 'image',
												'image' => $image
											  )
										)."</td>";
			if($image['order']==1){
			$table_row .= "<td><input type='radio' name='image_title' value='$x' checked='checked' /></td>";	
			}
			else{
			$table_row .= "<td><input type='radio' name='image_title' value='$x' /></td>";	
			}
			//delete link
			$table_row .= "<td>".elgg_view('output/confirmlink',array(
												'href' => $vars['url'] . "action/{$CONFIG->pluginname}/delete_image?stores=" . $vars['entity']->getGUID()."&path=".$image['path'],
												'text' => elgg_echo("delete"),
												'confirm' => elgg_echo("stores:delete:confirm"),
											))."</td></tr>";  
			$x++;
		}
		
		$image_count = count($images);
			
		$form_body = <<<EOT
        	<script>
        		
        		function load_edit_product_detaile(){
					 $("#product_file_change").show();
				}
        	</script>
        	
		<script type="text/javascript" src="{$CONFIG->wwwroot}mod/{$CONFIG->pluginname}/js/multipleupload.js"></script> 
        <script type="text/javascript" src="{$CONFIG->wwwroot}mod/{$CONFIG->pluginname}/js/moveupdown.js"></script> 	
        	<form action="{$vars['url']}action/{$action}" enctype="multipart/form-data" method="post">
				<p>
					<label><span style="color:red">*</span>{$title_label}</label><br />
					{$title_textbox}
					
				</p>
				
				------------------
				{$product_cat}
				<div id="change_by_product_type">
					<p>
						<label><span style="color:red">*</span>{$category_label}</label><br />
						{$category_view}
					</p>
				</div>
				<p>
					{$country_details}
					--------------------------------
				</p>
				<p>
					<label><span style="color:red">*</span>{$text_label}</label><br />
					{$text_textarea}
				</p>

		
				<p name="files_div" id="files_div">
					File: &nbsp;
					<input type="file" name="userfile[]" id="file_0" size="30" onChange="javascript:add_file(this.value, {$image_count});">
				</p>
				
				
				<br><br>
				
	
				<p>
					<table id="imageTable" style="display: {$display};" cellspacing="10" border="1">
					  <tbody>
					    <tr>
					      <td>Image</td><td style='width:100px;'>Title</td><td>Delete</td>
					    </tr>
					    {$table_row}
					  </tbody>
					</table>				
				</p>
				<div id="product_type_fields" >
					{$fields}
					{$cstom_fields}
				</div>
				<p>
					<label>{$date_from_label}</label><br />
					{$date_from_input}
				</p>
				<p>
					<label>{$date_until_label}</label><br />
					{$date_until_input}
				</p>				
				<p>
					<label>{$tag_label}</label><br />
					{$tag_input}
				</p>
				<p>
					<label>{$access_label}</label><br />
					{$access_input}
				</p>
				<p>
					{$entity_hidden}
					{$submit_input}
				</p>
				
		
		
			</form>
EOT;
echo $form_body;
?>
